package cn.xianshu.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class CheckLoginFilter extends ZuulFilter {


    @Override
    public String filterType() {
        return "pre"; // 前置拦截
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 返回值决定了是否要执行run方法
        // 判断请求的URL是不是login、register 登录和注册
        // 返回false不执行run方法因为不需要做登陆检查
        // 1.获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        // 2.获取请求的url
        String RequestURI = request.getRequestURI();
        // 3.判断是否要排除
        if (RequestURI.endsWith("login") || RequestURI.endsWith("register")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 核心方法做登陆检查
        // 拿到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 2.拿到请求头的Token
        String token = request.getHeader("token");
        // 3.如果Token为空，为没登陆
        if (StringUtils.isEmpty(token)){
            // 3.1返回一个请求登录错误提示
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("application/json;charset = utf-8"); // 设置 为json格式
                response.getWriter().write("请登录!");
            } catch (Exception e) {
                e.printStackTrace();
            }
            // 3.2 阻止继续往后执行
            currentContext.setSendZuulResponse(false);
        }
        // 4.如果token不为空  放行
        return null;
    }

}
